﻿// -----------------------------------------------------------------------
// <copyright file="RegexNode.cs" company="Microsoft">
// TODO: Update copyright text.
// </copyright>
// -----------------------------------------------------------------------

namespace FxCopContrib.Experimental.RegexCop
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Reflection;
    using System.Text.RegularExpressions;
    using System.Collections;

    public class RegexNode : PrivateReflectionWrapper
    {
        private static readonly Assembly RegexAssembly = typeof(Regex).Assembly;
        private const string _RegexNodeTypeFullName = "System.Text.RegularExpressions.RegexNode";
        private static readonly Type _RegexNodeType = RegexAssembly.GetType(_RegexNodeTypeFullName);

        public RegexOptions RegexOptions
        {
            get
            {
                return GetFieldValue<RegexOptions>("_options");
            }
        }

        public RegexNode() : base(_RegexNodeType)
        {
        }

        internal RegexNode(object internalRegexNode)
            : base(_RegexNodeType, internalRegexNode)
        {
        }

        public IEnumerable<RegexNode> Children
        {
            get
            {
                return ToEnumerable<RegexNode>("_children");
            }
        }

        public RegexNodeType NodeType
        {
            get
            {
                return GetFieldValue<RegexNodeType>("_type");
            }
        }

        public int Min
        {
            get
            {
                return GetFieldValue<int>("_m");
            }
        }

        public int Max
        {
            get
            {
                return GetFieldValue<int>("_n");
            }
        }

        public RegexCharClass CharClass
        {
            get
            {
                if (NodeType == RegexNodeType.Set
                    || NodeType == RegexNodeType.Setloop
                    || NodeType == RegexNodeType.Setlazy
                    )
                {
                    return RegexCharClass.FromString(GetFieldValue<string>("_str"));
                }
                else if (NodeType == RegexNodeType.One
                    || NodeType == RegexNodeType.Oneloop
                    || NodeType == RegexNodeType.Onelazy
                    || NodeType == RegexNodeType.Notone
                    || NodeType == RegexNodeType.Notoneloop
                    || NodeType == RegexNodeType.Notonelazy
                    )
                {
                    return RegexCharClass.FromChar(GetFieldValue<char>("_ch"));
                }
                return null;
            }
        }

        public override string ToString()
        {
            return GetFieldValue<string>("_str");
        }
    }
}
